package com.seean.site.core.tree;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.util.List;
import java.util.Map;

/**
 * @authur wsx
 * @date 2020/5/27 14:51
 */
public class NTreeUtil {

    private List<Tree> rootList; // 根节点对象存放到这里
    private List<Tree> bodyList; // 其他节点存放到这里，可以包含根节点

    public NTreeUtil(List<Tree> rootList, List<Tree> bodyList) {
        this.rootList = rootList;
        this.bodyList = bodyList;
    }

    public List<Tree> getTree() { // 调用的方法入口
        if (bodyList != null && !bodyList.isEmpty()) {
            // 声明一个map，用来过滤已操作过的数据
            Map<String, String> map = Maps.newHashMapWithExpectedSize(bodyList.size());
            rootList.forEach(beanTree -> getChild(beanTree, map));
            return rootList;
        }
        return null;
    }

    private void getChild(Tree beanTree, Map<String, String> map) {
        List<Tree> childList = Lists.newArrayList();
        bodyList.stream().filter(c -> !map.containsKey(c.getId())).filter(c -> c.getParentId().equals(beanTree.getId()))
                .forEach(c -> {
                    map.put(c.getId(), c.getParentId());
                    getChild(c, map);
                    childList.add(c);
                });
        beanTree.setChildren(childList);
    }
}
